import 'dart:async';
import 'package:flutter/material.dart';
import 'package:connectivity/connectivity.dart';

class PhoneSignal extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => new PhoneSignalState();
}

class PhoneSignalState extends State<PhoneSignal> {
  // 网络状态检测结果
  String _connectionStatus = 'Unknown';
  // 网络状态检测实例
  StreamSubscription<ConnectivityResult> _subscription;

  @override
  void initState() {
    super.initState();
    // 检测当前网络状态
    initConnectivity();
    // 监听网络状态，当网络状态改变时，获取最新的网络状态
    _subscription = Connectivity()
        .onConnectivityChanged
        .listen((ConnectivityResult result) {
      setState(() {
        _connectionStatus = result.toString();
      });
    });
  }

  Future<Null> initConnectivity() async {
    String connectionStatus;
    //平台消息可能会失败，因此我们使用Try/Catch PlatformException。
    try {
      connectionStatus = (await Connectivity().checkConnectivity()).toString();
    } catch (e) {
      print(e.toString());
      connectionStatus = '信号检测失败！';
    }

    // 如果在异步平台消息运行时从树中删除了该小部件，
    // 那么我们希望放弃回复，而不是调用setstate来更新我们不存在的外观。
    if (!mounted) {
      return;
    }

    setState(() {
      _connectionStatus = connectionStatus;
    });
  }

  @override
  dispose() {
    super.dispose();
    // widget销毁时，取消网络状态的监听
    _subscription.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return _connectionStatus == 'ConnectivityResult.none'
        ? Container(
            padding: EdgeInsets.only(
              left: 16,
            ),
            height: 32,
            color: Color.fromRGBO(255, 240, 214, 1),
            child: Row(
              children: <Widget>[
                Container(
                  padding: EdgeInsets.only(
                    right: 6,
                  ),
                  child: Image(
                    image: AssetImage('assets/images/no_signal.png'),
                    width: 14,
                    height: 14,
                  ),
                ),
                Text(
                  '无网络连接，请检查你的网络',
                  style: TextStyle(
                    color: Color.fromRGBO(239, 145, 5, 1),
                    height: 16 / 12,
                    fontSize: 12,
                  ),
                ),
              ],
            ),
          )
        : SizedBox();
  }
}
